/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PuserList.java
 *
 * Created on 3 mai 2011, 10:20:26
 */
package frame;

import commun.Message;
import java.awt.Color;
import java.awt.Component;
import java.rmi.RemoteException;
import java.util.ArrayList;

import java.util.Hashtable;
import java.util.Map;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListCellRenderer;
import server._ZoneExchange;

import user.User;

/**
 *
 * @author sz
 */
public class PuserList extends javax.swing.JPanel {
    private Hashtable listFmessage;
    /** Creates new form PuserList */
    public PuserList() {
        initComponents();
        this.initUsers();
    }

    public PuserList(_ZoneExchange zEx, String idUser) {
        initComponents();
        this.listFmessage = new Hashtable();
        this.messages = new ArrayList<Message>();
        this.zEx = zEx;
        this.idUser = idUser;
        this.lUsers.setCellRenderer(new MyCellRenderer());
        this.initUsers();


    }

public void initUsers()
 {
   try {User[] users = zEx.getAllFriends(this.idUser);
      model = new DefaultListModel();
   for (int i = 0; i < users.length; i++) {
	model.addElement(users[i]);
	}
        lUsers.setModel(model);
    } catch (RemoteException e) {
JOptionPane.showMessageDialog(null, "Problem of connection server");

		}

}
public void updateUserlist(User[] users) {
		model.removeAllElements();
		for (int i = 0; i < users.length; i++) {
			model.addElement(users[i]);
		}
	}

	public void addUser(User user) {
		model.addElement(user);
	}

public void receiveMessage(Message message) {
    User tmp = null;

    for (int i = 0; i < model.size(); i++) {
        tmp = (User) model.getElementAt(i);
        if (tmp.getUserId().equals(message.getFromId())) {
            tmp.setGetMessage(true);
            messages.add(message);
            model.remove(i);
            model.add(i, tmp);
            break;
        }
    }
    for(Message val : this.messages){
        if(this.listFmessage.containsKey(val.getFromId())){
            Fmessage f = (Fmessage)this.listFmessage.get(val.getFromId());
            f.displayMsg(val);
        }
    }
}



 class MyCellRenderer extends JLabel implements ListCellRenderer {
	 ImageIcon boyIcon = null;

	 ImageIcon boygray = null;

	 ImageIcon girlIcon = null;

	 ImageIcon girlgray = null;

        public MyCellRenderer() {
            try {
			String imgurl = ClassLoader.getSystemResource("ressources/img/boy1.jpg")
					.toString().substring(6);
			boyIcon = new ImageIcon(imgurl);
			imgurl = ClassLoader.getSystemResource("ressources/img/girl1.jpg").toString()
					.substring(6);
			girlIcon = new ImageIcon(imgurl);
			imgurl = ClassLoader.getSystemResource("ressources/img/boy2.jpg").toString()
					.substring(6);
			boygray = new ImageIcon(imgurl);
			imgurl = ClassLoader.getSystemResource("ressources/img/girl2.jpg").toString()
					.substring(6);
			girlgray = new ImageIcon(imgurl);
            } catch (Exception e) {
                    e.printStackTrace();
            }
	}

	// This is the only method defined by ListCellRenderer.
	// We just reconfigure the JLabel each time we're called.

	public Component getListCellRendererComponent(JList list, Object value, // value
																			// to
																			// display
			int index, // cell index
			boolean isSelected, // is the cell selected
			boolean cellHasFocus) // the list and the cell have the focus
	{
		User tmp = (User) value;
                String id=tmp.getUserId();
                String userName=tmp.getUserName();
                String sex=tmp.getSex();
		boolean online=tmp.isOnline();

		this.setText(userName + "(" + id +")");

		ImageIcon img = null;

                if(sex.equals("male"))
                {
                  if (online) {
		    img = boyIcon;
		  } else {
		    img = boygray;
		  }
                }
                else
                {
                  if (online)
				img = girlIcon;
			else
				img = girlgray;
                }
              this.setIcon(img);
		if (isSelected) {
			setBackground(list.getSelectionBackground());
			setForeground(list.getSelectionForeground());
		} else {
			setBackground(list.getBackground());
			setForeground(list.getForeground());
		}
              this.setEnabled(list.isEnabled());
              this.setFont(list.getFont());
              if(tmp.isGetMessage())
                  this.setForeground(Color.RED);
              this.setOpaque(true);
              return this;
	}
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pUsers = new javax.swing.JScrollPane();
        lUsers = new javax.swing.JList();

        setLayout(new java.awt.BorderLayout());

        lUsers.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        lUsers.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lUsersMouseClicked(evt);
            }
        });
        pUsers.setViewportView(lUsers);

        add(pUsers, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void lUsersMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lUsersMouseClicked
        // TODO add your handling code here:
        if (evt.getClickCount() == 2) {
   JList users = (JList) evt.getSource();
   int index = users.locationToIndex(evt.getPoint());
  DefaultListModel modeltmp=(DefaultListModel)users.getModel();
 User tmp = (User) model.getElementAt(index);
 ArrayList tmpMessages = new ArrayList();;
 for(int i=0;i<messages.size();i++)
 {    Message ms=(Message)messages.get(i);
      if(ms.getFromId().equals(tmp.getUserId()))
      {
         tmpMessages.add(ms);
      }
 }

 Fmessage fmessage;
if (tmp.isGetMessage()) {
fmessage = new Fmessage(tmpMessages,this.zEx);

tmp.setGetMessage(false);
model.remove(index);
model.add(index, tmp);
this.listFmessage.put(idUser, fmessage);
}
 else
{
    fmessage = new Fmessage(null,this.zEx);
}

fmessage.setVisible(true);
}

    }//GEN-LAST:event_lUsersMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList lUsers;
    private javax.swing.JScrollPane pUsers;
    // End of variables declaration//GEN-END:variables

 private _ZoneExchange zEx;
 private  String idUser;

 private DefaultListModel model;

 private ArrayList<Message> messages ;

}
